package com.dzu.medium;

import com.dzu.common.ListNode;

/**
 * @author ZhaoDong
 * @date 2023/1/5 10:22
 * @description 19. 删除链表的倒数第 N 个结点
 */
public class Test19 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
//        ListNode l3 = new ListNode(3);
//        ListNode l4 = new ListNode(4);
//        ListNode l5 = new ListNode(5);

        l1.next = l2;
//        l2.next = l3;
//        l3.next = l4;
//        l4.next = l5;


        System.out.println(removeNthFromEnd(l1, 2));

    }

    // 双指针
    public ListNode removeNthFromEnd3(ListNode head, int n) {
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;

        ListNode slow  = dummyHead;
        ListNode fast = dummyHead;

        while(n>0 && fast.next != null){
            n--;
            fast = fast.next;
        }

        while(fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummyHead.next;
    }

    public static int cut = 0;

    public static ListNode removeNthFromEnd2(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        head.next = removeNthFromEnd2(head.next, n);
        cut++;
        if (n == cut) {
            return head.next;
        }
        return head;
    }



    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }

        ListNode temp = head;
        ListNode per = new ListNode(-1);
        ListNode res = per;
        per.next = head;

        int count = 1;

        while (temp != null) {
            if (count > n) {
                per = per.next;
            }

            count++;
            temp = temp.next;
        }
        per.next = per.next.next;
        return res.next;
    }
}
